package finalgame.GUI.stage;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;

import finalgame.Game;
import finalgame.Util;
import finalgame.Engine.trainer.Trainer;
import finalgame.GUI.Character;
import finalgame.Graphics.Location;
import finalgame.Graphics.RenderEngine;
import finalgame.Resources.ResourceLoader;

public class StageLoader {
	public static Stage load(File map) throws IOException, JSONException {
		BufferedReader in = new BufferedReader(new InputStreamReader(
				ResourceLoader.getResourceAsStream(map)));
		String name = in.readLine();
		String textureName = in.readLine();
		String texture = "image/level/" + textureName;
		String textureType = Util.getExtension(textureName).toUpperCase();
		Texture tex = TextureLoader.getTexture(textureType,
				ResourceLoader.getResourceAsStream(texture, true));
		Stage stage = new Stage(tex);
		JSONArray trainers = new JSONArray(in.readLine());
		for(int i = 0; i < trainers.length(); i++) {
			JSONObject trainer = trainers.getJSONObject(i);
			String tName = trainer.getString("name");
			String type = trainer.getString("type");
			JSONArray loc = trainer.getJSONArray("pos");
			Location tLoc = new Location(loc.getInt(0), loc.getInt(1));
			stage.addTrainer(type, tName, tLoc);
		}
		StageMap.addStage(name, stage);
		return stage;
	}
}
